<template>
    <div class="rx-upload">
        <uv-loading-icon v-if="flower"></uv-loading-icon>
        <uni-file-picker
            ref="file"
            v-model="files"
            :readonly="readOnly"
            :delIcon="false"
            :limit="fileLimit"
            mode="list"
            :autoUpload="false"
            :fileMediatype="fileMediatype"
            :fileExtname="fileExtname"
            @select="selectFile"
        >
            <template class="rx-upload-list" #file="{file,index}">
                <div class="officeLayout">
                    <i :class="['iconfont',getIconfont(file)]"></i>
                    <div class="officeLayout-name">{{ file.name }}</div>
                    <view class="officeLayout-icon">
                        <my-icon v-if="getIcon(file) ==7"  @click.stop="previewImage(file)" type="icon-icon-test-copy"></my-icon>
                        <my-icon @click="preViewOfficeDome(file)" type="icon-cloud-download"></my-icon>
                        <my-icon v-if="canDel(file)" @click.stop="removeSelect(index)" type="icon-Vue3_delete"></my-icon>
                    </view>
                </div>
            </template>
            <template #button>
                <button class="upload-button">
                    <i style="margin-right: 0.5rem;font-size: 1.2rem" class="iconfont icon-lineshangchua"></i>
                    <span>{{ i18n('uploadAtta', '上传附件') }}</span>
                </button>
            </template>
        </uni-file-picker>
    </div>
    <RxEmpty v-if="readOnly && files.length==0"></RxEmpty>
</template>

<script>
import MForm from '../js/MForm';
import {FormApi} from "@/api/FormApi.js";
import FormBase from "../js/FormBase";
import RxEmpty from "@/components/RxEmpty"

export default {
    name: "MUpload",
    mixins: [MForm,FormBase],
    components:{RxEmpty},
    data() {
        return {
            files: [],
            flower: false,
            fileType: {//类名
                image: ['img', 'png', 'jpg', 'jpeg', 'svg'],
                media: ['mp3', 'mp4', 'avi', 'rmvb'],
                compressed: ['zip', 'rar','apk'],
                office: ['ppt', 'pptx', 'xls', 'xlsx', 'doc', 'docx'],
                pdf: ['pdf'],
                email: ['eml'],
                axure: ['rp'],
                xmind: ['xmind'],
                certificate: ['p12', 'pfx', 'cer'],
                cipher: ['pem'],
                txt: ['txt']
            },
            fileExtname: '',
            fileLimit: this.metadata.options.isSingle ? 1 : this.metadata.options.amount || 9,
            fileMediatype:''
        }
    },
    mounted() {
        // #ifdef H5
       this.fileMediatype = 'all'
        // #endif
        // #ifdef APP-PLUS
        this.fileMediatype = 'image'
        // #endif
        this.init();
        this.initValue(this.value);
    },
    methods: {
        canDel(item) {
            if(this.readOnly){
                return false;
            }
            //如果文件是上传状态则直接保存.
            if(!item.save){
                return true;
            }
            //获取当前字段的权限
            let fieldPermission=this.getPermission(this.metadata);
            if(!fieldPermission || fieldPermission.del == undefined){
                return true;
            }
            return fieldPermission.del;
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        init() {
            let conf = this.metadata.options;
            //判断
            let extensionList = [];

            if (conf.uploadType && conf.uploadType.length != 0) {
                conf.uploadType.forEach(res => {
                    if (this.fileType[res]) {
                        extensionList.push(...this.fileType[res]);
                    }
                })
            } else {
                if (conf.attachType == 'office') {
                    extensionList = [
                        ...this.fileType['office']
                    ];
                } else if (conf.attachType == 'pdf') {
                    extensionList = [
                        ...this.fileType['pdf']
                    ];
                } else {
                    extensionList = [
                        ...this.fileType['image'],
                        ...this.fileType['media'],
                        ...this.fileType['office'],
                        ...this.fileType['pdf'],
                        ...this.fileType['txt']
                    ];
                }
            }
            this.fileExtname = extensionList.join(",");
        },
        selectFile(e) {
            let curFile = e.tempFiles[0];
            if ((curFile.size / (1024 * 1024)) > this.metadata.options.size) {
                uni.showToast({
                    title:this.i18n('optionsSize','上传文件大于指定大小') + this.metadata.options.size + "M！",
                    duration: 1500,
                    icon: 'none'
                });
                this.$refs.file.clearFiles(this.files.length - 1);
                return;
            }
            this.flower = true;
            var imageSrc = e.tempFilePaths[0];
            FormApi.upload({
                filePath: imageSrc,
            }).then(res => {
                this.flower = false;
                this.handFiles(res.data);
            })
        },
        handFiles(json) {
            var aryFiles = json.data;
            for (var i = 0; i < aryFiles.length; i++) {
                var file = aryFiles[i];
                this.files.push({
                  extname: file.ext,
                  id: file.fileId,
                  size: file.totalBytes,
                  name: file.fileName,
                  system: file.fileSystem,
                  path: file.path,
                  user: file.createUser,
                  time: file.createTime
                });
            }
        },
        initValue(val) {
            if (!val) return [];

            var fileAry = JSON.parse(val);
            this.files = fileAry;
        },
        preViewOfficeDome(file) {
            var isOffice = false;
            var isImage = false;
            var mediaType = [
                ...this.fileType['media'],
                ...this.fileType['office'],
                ...this.fileType['pdf'],
                ...this.fileType['txt'],
                ...this.fileType['compressed']
            ];
            var imageType = [
                ...this.fileType['image']
            ];
            let extName =  file.name.substring(file.name.lastIndexOf('.')+1);
            if (mediaType.contains(extName)) {
                isOffice = true;
            } else if (imageType.contains(extName)) {
                isImage = true;
            }
            if (!isOffice && !isImage) return;
            if (isOffice && this.canDown()) {
                // #ifdef H5
                uni.openDocument({
                    filePath: this.imageUrl(file.id),
                    success: function (res) {
                        console.log('打开文档成功');
                    }
                });
                // #endif
                // #ifdef APP-PLUS
                let self = this;
                uni.downloadFile({
                    url: self.imageUrl(file.id), //仅为示例，并非真实的资源
                    success: (res) => {
                        if (res.statusCode === 200) {
                            uni.saveFile({//使用该功能，以将临时文件保存在手机中可长久存储的区域
                                tempFilePath: res.tempFilePath,
                                success: (saveResult) => {
                                    console.log(saveResult.savedFilePath)
                                    uni.showToast({
                                        title:self.i18n('saveFile','下载成功')+saveResult.savedFilePath, // 消息内容
                                        duration: 2000, // 持续时间（单位：毫秒）
                                        icon: 'none' // 图标类型（可选值：success/loading/none）
                                    });
                                    // 在保存文件成功后，使用 uni.openDocument 方法打开文件
                                    // uni.openDocument({
                                    //     filePath: saveResult.savedFilePath,
                                    //     success: function () {
                                    //         console.log("文件打开成功!");
                                    //         //至此，手机会从app中跳转到文件预览界面
                                    //         //之后可从预览界面返回app中
                                    //     },
                                    //     fail: function (err) {
                                    //         console.log('打开失败', err);
                                    //     },
                                    // });
                                }
                            })
                        }
                    }
                });
                // #endif
            } else if (isImage) {
                let current = 0;
                let imgsArray = [];
                this.files.forEach(item => {
                    if (this.getIcon(item) == 7) {
                        if (item.id == file.id) {
                            current = imgsArray.length;
                        }
                        imgsArray.push(this.imageUrl(item.id));
                    }
                })
                uni.previewImage({
                    current: current,
                    urls: imgsArray
                });
            }
        },
        canDown(){
            //获取当前字段的权限
            let fieldPermission=this.getPermission(this.metadata);
            if(!fieldPermission || fieldPermission.down == undefined){
                return true;
            }
            return fieldPermission.down;
        },
        getIcon(file) {
            if (!file) return;
            let extName = file.extname;
            if(!extName){
                let nameType = file.name.split('.')
                extName = nameType[nameType.length-1]
            }
            if (!extName) return;
            if (this.fileType['media'].contains(extName)) {
                return 1;
            } else if (['xls', 'xlsx'].contains(extName)) {
                return 2;
            } else if (['doc', 'docx'].contains(extName)) {
                return 3;
            } else if (['ppt', 'pptx'].contains(extName)) {
                return 4;
            } else if (this.fileType['txt'].contains(extName)) {
                return 5;
            } else if (this.fileType['pdf'].contains(extName)) {
                return 6;
            } else if (this.fileType['image'].contains(extName)) {
                return 7;
            }
        },
        /**
         * 删除选测图片
         */
        removeSelect(idx) {
            this.files.splice(idx, 1);
        },
        //预览图片
        previewImage(file){
            uni.previewImage({
                current: 1,
                urls: [this.imageUrl(file.id)]
            });
        },
        getIconfont(file) {
            let extName = file.extname;
            if(!extName){
                let nameType = file.name.split('.')
                extName = nameType[nameType.length-1]
            }
            var mediaType = ['mp3', 'mp4', 'avi', 'rmvb'];
            var zipTtp = ['zip', 'rar'];
            var pptType = ['ppt', 'pptx'];
            var pdfType = ['pdf'];
            var docType = ['doc', 'docx']
            var xlsType = ['xls', 'xlsx'];
            var txtType = ['txt'];
            var picType = ['jpg', 'png', 'jpeg'];
            if (mediaType.contains(extName)) {
                return 'icon-file-Audio-fill';
            }
            if (zipTtp.contains(extName)) {
                return 'icon-file-zip2-fill';
            } else if (xlsType.contains(extName)) {
                return 'icon-file-markdown-fill';
            } else if (docType.contains(extName)) {
                return 'icon-file-word-fill';
            } else if (pptType.contains(extName)) {
                return 'icon-file-excel-fill';
            } else if (txtType.contains(extName)) {
                return 'icon-file-txt-fill1';
            } else if (pdfType.contains(extName)) {
                return 'icon-file-pdf2-fill';
            } else if (picType.contains(extName)) {
                return 'icon-file-image-fill';
            } else {
                return 'icon-wenjianziliao'
            }
        }
    },
    watch: {
        files: {
            handler(newValue, oldValue) {
                var str = JSON.stringify(newValue);
                this.updateValue(str);
            },
            deep: true
        },
        value: function (val, oldVal) {
            if (val != oldVal) {
                this.triggerEmitEvents('change', val, this.data)
                this.initValue(val);
            }
        },
    }
}
</script>

<style scoped>
.upload-button {
    width: 100%;
    height: 2rem;
    line-height: 2rem;
    text-align: center;
    border: solid 1px rgba(217, 217, 217, 1);
    color: rgba(0, 0, 0, 0.85);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
}

.rx-upload >>> .uni-file-picker__item {
    padding: 0px !important;
}

.rx-upload >>> .uni-file-picker__lists {
    border-style: none !important;
}

.rx-upload >>> .files-border {
    border: none !important;
}

.rx-upload {
    margin-right: .5rem;
}
.officeLayout {
    width: 100%;
    font-size: 14px;
    padding: 0.2rem 0;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.officeLayout-name {
    white-space: nowrap;
    color: #555;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    flex: 1;
    text-align: left;
    margin-left: 1rem;
    margin-right: 0.5rem;
}
.officeLayout-icon  i{
    color: rgba(66, 133, 244, 1);
    font-size: 1.3rem!important;
    margin-left: 0.5rem;
}
.officeLayout i {
    font-size: 1.6rem;
}
.icon-file-Audio-fill{
    color: rgba(255, 125, 0, 1);
}
.icon-file-zip2-fill{
    color: rgba(255, 191, 67, 1);
}
.icon-file-markdown-fill{
    color: rgba(66, 133, 244, 1);
}
.icon-file-word-fill{
    color: rgba(66, 133, 244, 1);
}
.icon-file-image-fill{
    color: rgba(252, 89, 89, 1);
}
.icon-file-excel-fill{
    color: rgba(0, 186, 173, 1);
}
.icon-file-txt-fill1{
    color: rgba(255, 191, 67, 1);
}
.icon-file-pdf2-fill{
    color: rgba(252, 89, 89, 1);
}
.icon-file-unknown-fill{
    color: rgba(166, 166, 166, 1);
}
</style>
